package org.opens.javaskill.design.apply;

import java.util.Random;

/**
 * 功能:
 * <p>这个设计模式的名称是-二阶段终结模式</p>
 * @Date 2020/9/22 20:37
 * @Created by 99126
 */
public class TwoPhaseTerminationPattern {

    public static void main(String[] args) {
        CounterIncrement counterIncrement = new CounterIncrement();

        counterIncrement.start();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        counterIncrement.close();
    }

}

class CounterIncrement extends Thread {

    private volatile boolean terminated = false;

    private int count = 0;

    private Random random = new Random(System.currentTimeMillis());

    @Override
    public void run() {
        try {
            while (!terminated) {
                System.out.println(this.getName() + " " + (count++));
                Thread.sleep(random.nextInt(1000));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 使用finally代码块来确保使用的资源会被释放掉.
            this.clean();
        }
    }

    public void clean() {
        System.out.println("释放资源ing");
        try {
            Thread.sleep(random.nextInt(1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("资源释放完毕");
    }

    public void close() {
        this.terminated = true;
        this.interrupt();
    }

}